import com.sun.corba.se.impl.resolver.SplitLocalResolverImpl;

import java.util.ArrayList;

public class No029 {
    /**
     * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字，
     * 例如，如果输入如下4 X 4矩阵：
     * 1   2  3  4
     * 5   6  7  8
     * 9  10 11 12
     * 13 14 15 16
     * 则依次打印出数字
     * 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
     */
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
        System.out.println(printMatrix(matrix));
    }

    public static ArrayList<Integer> printMatrix(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList<>();
        if (matrix.length == 0) return result;
        int rowDown = matrix.length;
        int colRight = matrix[0].length;
        int row = 0, col = 0, rowUp = 0, rowLeft = -1, count = 0;
        while (count < (matrix.length * matrix[0].length)) {
            //右
            while (col < colRight && count < (matrix.length * matrix[0].length)) {
                result.add(matrix[row][col++]);
                count++;
            }
            colRight--;
            col--;
            row++;
            //下
            while (row < rowDown && count < (matrix.length * matrix[0].length)) {
                result.add(matrix[row++][col]);
                count++;
            }
            rowDown--;
            row--;
            col--;
            //左
            while (col > rowLeft && count < (matrix.length * matrix[0].length)) {
                result.add(matrix[row][col--]);
                count++;
            }
            rowLeft++;
            col++;
            row--;
            //上
            while (row > rowUp && count < (matrix.length * matrix[0].length)) {
                result.add(matrix[row--][col]);
                count++;
            }
            rowUp++;
            row++;
            col++;
        }
        return result;
    }
}
